package task

import (
	"log"
	"redis-push/pkg/config"
	"redis-push/pkg/db"
	"redis-push/pkg/instance"
	"sync"
)

func RunTasks() (err error) {
	instances := []instance.Instance{}
	err = db.New().Find(&instances).Error
	if err != nil {
		return
	}
	// 限制最大并发
	max := make(chan struct{}, 100)
	var wg sync.WaitGroup
	defer close(max)
	for i := range instances {
		max <- struct{}{}
		wg.Add(1)
		go func(i int) {
			logs, err := instances[i].GetSlowlogs()
			if err != nil {
				log.Println("获取慢日志失败", err)
			} else if len(logs) > 0 {
				err = instance.PushSlowlogsToES(logs, &config.NewHandler().ESConfig)
				if err != nil {
					log.Println("写入ES失败", err)
				}
			}
			<-max
			wg.Done()
		}(i)
	}
	wg.Wait()
	log.Println("收集完成")
	return
}
